package com.bw.liuyushan.zhuangao4_weektest2.MVP.Fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bw.liuyushan.mvp_lib.View.BaseFragment;
import com.bw.liuyushan.zhuangao4_weektest2.Adapter.GiftAdapter;
import com.bw.liuyushan.zhuangao4_weektest2.Adapter.TalkAdapter;
import com.bw.liuyushan.zhuangao4_weektest2.Adapter.VideoAdapter;
import com.bw.liuyushan.zhuangao4_weektest2.DaoSQL.UserMsg;
import com.bw.liuyushan.zhuangao4_weektest2.DaoSQL.UserMsgDao;
import com.bw.liuyushan.zhuangao4_weektest2.DaoSQL.UserMsgUtils;
import com.bw.liuyushan.zhuangao4_weektest2.Entity.GiftBean;
import com.bw.liuyushan.zhuangao4_weektest2.Entity.VideoBean;
import com.bw.liuyushan.zhuangao4_weektest2.MVP.Activity.UserActivity;
import com.bw.liuyushan.zhuangao4_weektest2.MVP.Contrack.IContrackTest;
import com.bw.liuyushan.zhuangao4_weektest2.MVP.Model.BaseModelTest;
import com.bw.liuyushan.zhuangao4_weektest2.MVP.Presenter.BasePresenterTest;
import com.bw.liuyushan.zhuangao4_weektest2.R;
import com.bw.liuyushan.zhuangao4_weektest2.UI.MyStand;
import com.bw.liuyushan.zhuangao4_weektest2.Utils.VideoLayoutManager;
import com.bw.liuyushan.zhuangao4_weektest2.zhifubao.PayResult;
import com.bw.liuyushan.zhuangao4_weektest2.zhifubao.util.OrderInfoUtil2_0;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ZhuanGao4_WeekTest2
 * file name is : Fragment_Main1
 * created by Ender on 2021/8/23 8:31.
 * author : 刘雨杉
 * Describe(作用):
 */
public class Fragment_Table2 extends BaseFragment<BasePresenterTest> implements IContrackTest.C_ViewTest, OnRefreshLoadMoreListener {
    private SmartRefreshLayout smVideo;
    private RecyclerView rvVideo;
    int currentPage = 8;//页数
    VideoAdapter adapter;
    boolean isVideo;
    PopupWindow popupWindow;
    GiftAdapter giftAdapter;
    //    String name;
    boolean isLogin;
    String namesp;
    UserMsg user;
    int price = 0;//支付宝金额变量
    private RecyclerView talklist;
    private EditText talk;
    private Button send;
    List<GiftBean.DataBean> data2;
    TextView yue;


    UserMsg unique;

    @Override
    public int bindLayout() {
        return R.layout.fragment_table2;
    }

    @Override
    public void initView() {
        //防止内存泄露
        ip = new BasePresenterTest(new BaseModelTest(), this);

        smVideo = (SmartRefreshLayout) findViewById(R.id.sm_Video);
        rvVideo = (RecyclerView) findViewById(R.id.rv_Video);

        smVideo.setOnRefreshListener(this);
        smVideo.setOnRefreshLoadMoreListener(this);
//        rvVideo.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
        //设置布局管理器
        rvVideo.setLayoutManager(new VideoLayoutManager(getContext()));
        //设置滚动监听
        rvVideo.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                        MyStand myStand = layoutManager.getChildAt(0).findViewById(R.id.stand);
                        myStand.startPlayLogic();
                        break;
                }
            }
        });

        talklist = (RecyclerView) findViewById(R.id.talklist);
        talk = (EditText) findViewById(R.id.talk);
        send = (Button) findViewById(R.id.send);
        talklist.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    @Override
    public void initDate() {
        SharedPreferences sp = getActivity().getSharedPreferences("sp", Context.MODE_PRIVATE);
        isLogin = sp.getBoolean("isLogin", false);
        namesp = sp.getString("namesp", null);
        List<String> list = new ArrayList<>();
        ip.mpVideo("zytestapi/video/findVideos?pageSize=10&currentPage=" + currentPage);
        ip.mpGift();
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = talk.getText().toString();

                //打住
                list.add(string);
                //写适配器去
                TalkAdapter talkAdapter = new TalkAdapter(list);
                talklist.setAdapter(talkAdapter);
                talkAdapter.notifyDataSetChanged();
                talklist.smoothScrollToPosition(list.size());
                talk.setText("");
            }
        });

    }

    @Override
    public void ShowVideo(VideoBean videoBean) {
        List<VideoBean.DataBean> data = videoBean.getData();
        initAdapter(data);
    }

    private void initAdapter(List<VideoBean.DataBean> data) {
        smVideo.finishLoadMore();
        smVideo.finishRefresh();
        if (adapter == null) {
            adapter = new VideoAdapter(data);
            rvVideo.setAdapter(adapter);
        } else {
            if (isVideo) {
                adapter.getData().clear();
            }
            adapter.getData().addAll(data);
            adapter.notifyDataSetChanged();
        }
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if(isLogin){
                    unique = UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Username.eq(namesp)).unique();
                    if (unique == null) {
                        ToastUtils.showShort("登录信息失效,请重新登录");
                        Intent intent = new Intent(getActivity(), UserActivity.class);
                        startActivity(intent);
                    } else {
                        unique = UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Username.eq(namesp)).unique();
                        double price = unique.getPrice();
                        popupWindow = new PopupWindow(getContext());
                        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                        popupWindow.setHeight(750);

                        View popu = LayoutInflater.from(getContext()).inflate(R.layout.gift_popupwindow, null);
                        popupWindow.setContentView(popu);
                        popupWindow.setOutsideTouchable(true);//点击外部取消
                        popupWindow.showAtLocation(LayoutInflater.from(getContext()).inflate(R.layout.mystand, null), Gravity.BOTTOM, 300, 300);
                        RecyclerView viewById = popu.findViewById(R.id.rv_Giftpopu);
                        viewById.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
                        viewById.setAdapter(giftAdapter);
                        yue = popu.findViewById(R.id.yve);
                        yue.setText("当前余额为" + price);
                        popu.findViewById(R.id.getMonery).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (isLogin) {
                                    initPopuP();
                                } else {
                                    ToastUtils.showShort("尚未登录,请先登录");
                                    Intent intent = new Intent(getActivity(), UserActivity.class);
                                    startActivity(intent);
                                }

                            }
                        });

                    }
                }else{
                    ToastUtils.showShort("尚未登录,请先登录");
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isVideo = false;
        currentPage++;
        ip.mpVideo("zytestapi/video/findVideos?pageSize=10&currentPage=" + currentPage);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isVideo = true;
        currentPage = 8;
        ip.mpVideo("zytestapi/video/findVideos?pageSize=10&currentPage=" + currentPage);
    }

    @Override
    public void ShowGift(GiftBean giftBean) {
        data2 = giftBean.getData();
        giftAdapter = new GiftAdapter(data2);
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //接收登录时候的用户名

                if (isLogin) {//判断是否登录 未登录不能充值
                    user = UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Username.eq(namesp)).unique();
                    View popu = LayoutInflater.from(getContext()).inflate(R.layout.gift_popupwindow, null);
                    if (unique == null) {//查询对象为空shi
                        ToastUtils.showShort("登录信息失效,请重新登录");
                        Intent intent = new Intent(getActivity(), UserActivity.class);
                        startActivity(intent);
                    } else {

//                        user = UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Username.eq(namesp)).unique();
//                        View popu = LayoutInflater.from(getContext()).inflate(R.layout.gift_popupwindow, null);

//
                        if (unique.getPrice() <= 0) {
                            ToastUtils.showShort("账户余额不足,请先充值");
                            initPopuP();
                        } else {//账户余额足够时
                            UserMsg userMsg = new UserMsg();
                            userMsg.setId(unique.getId());
                            userMsg.setUsername(unique.getUsername());
                            userMsg.setPassword(unique.getPassword());
                            userMsg.setPrice(unique.getPrice() - data2.get(position).getPrice());
                            UserMsgUtils.getInstance().getDaoSession().update(userMsg);
//                            UserMsg unique = UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Username.eq(namesp)).unique();
//                            double price = unique.getPrice();
//                            yue.setText("当前余额为"+price);
//                    EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
//                    payV2();
                            ImageView imageView = new ImageView(getContext());
                            imageView.setX(400);
                            imageView.setY(800);
//                imageView.setLayoutParams(new ViewGroup.LayoutParams(60,60));//设置生成图片大小
                            getActivity().addContentView(imageView, new ViewGroup.LayoutParams(150, 150));
                            Glide.with(getContext()).load(data2.get(position).getGifImg()).into(imageView);
                            ObjectAnimator scaleX = ObjectAnimator.ofFloat(imageView, "scaleX", 1, 5);
                            ObjectAnimator scaleY = ObjectAnimator.ofFloat(imageView, "scaleY", 1, 5);
                            scaleX.setDuration(4000);
                            scaleY.setDuration(4000);
                            scaleX.start();
                            scaleY.start();
                            scaleX.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {//动画完成时的监听事件
                                    super.onAnimationEnd(animation);
                                    //透明消失效果
                                    ObjectAnimator.ofFloat(imageView, "alpha", 1, 0).setDuration(200).start();
                                }
                            });
                        }
                    }
                } else {
                    ToastUtils.showShort("尚未登录,请先登录");
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivity(intent);
                }

            }
        });

    }

    private void initPopuP() {
        PopupWindow popupWindow = new PopupWindow(getContext());
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(750);
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popumoney, null);
        popupWindow.setContentView(inflate);
        popupWindow.showAtLocation(LayoutInflater.from(getContext()).inflate(R.layout.mystand, null), Gravity.BOTTOM, 300, 300);
        popupWindow.setOutsideTouchable(true);


        inflate.findViewById(R.id.btn1_money200).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new AlertDialog.Builder(getActivity()).setIcon(R.drawable.money).setTitle("继续付款?").setMessage("充值成功后.概不退还!未成年人需在监护人知情情况下使用充值服务!")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                popupWindow.dismiss();
                            }
                        }).setPositiveButton("确认支付", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        price = 200;//支付宝金额变量
                        popupWindow.dismiss();
                        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                        payV2(price);

                    }
                }).create().show();
            }
        });
        inflate.findViewById(R.id.btn2_money400).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getActivity()).setIcon(R.drawable.money).setTitle("继续付款?").setMessage("充值成功后.概不退还!未成年人需在监护人知情情况下使用充值服务!")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                popupWindow.dismiss();
                            }
                        }).setPositiveButton("确认支付", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        price = 400;//支付宝金额变量
                        popupWindow.dismiss();
                        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                        payV2(price);
//                                        UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Username.eq(namesp)).unique().setPrice(200);
                    }
                }).create().show();
            }
        });
        inflate.findViewById(R.id.btn3_money648).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getActivity()).setIcon(R.drawable.money).setTitle("继续付款?").setMessage("充值成功后.概不退还!未成年人需在监护人知情情况下使用充值服务!")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                popupWindow.dismiss();
                            }
                        }).setPositiveButton("确认支付", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        price = 648;//支付宝金额变量
                        popupWindow.dismiss();
                        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                        payV2(price);
                    }
                }).create().show();
            }
        });
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        GSYVideoManager.onResume();
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.onPause();
    }


    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2021000117699214";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCFU1L5Jdh2YZa9CuhY92lXRhCTVQiLoacN2H1XybIOA7pVstWGpn5tXUxyHBSUfMHbHmmG6i4WMm1511+qsSAdATa5dZL8nGQzJ7AwjXN6Iq0bbPBsrB8WrAY2ORnWWF5NTO5weLFtx6WZ2vLm37/DJKdUEVt6EiFOiEu1VvkfPUCffK3wyL591jnv+JKtNuIBOAk6XQCchcjj48zvQcX5ufppchbwd6nPhEsR6vOFbTjmt9TNV78U0Sw6nvGx9nm99Zlt/+aMArAhnnpaSUV+L9mwIhWTqTFplZ6jDq5tRYpkEw72WiijwqA52EUf1/EHQ3zfWPPj94GAcroAb80DAgMBAAECggEAVcEPaFNQVGxWkUc3xSl1pv3Y4XrbITybf4tUq6d+kAcTzdVWA+KJBPzyk56+GffYlICOLYnolLxgr/K4hMiiuCU0trsKDNLmnASWDdSdhtxQ7Yf3aF6ZLHL/F9dIaBa0qRGnd84ZiVvVhw1OGPOnmvOzcJ4tcWnB5IpD7+J+H/nKOMFWoIbo8EPxQWRz1+FR+flFv2xGhmM7LGQN9ofrjsNNRkzReFh46Wv1i03y1D7KBRO/V2pRuIy1B7fUtRWGmm2hg7HwIwW8rqhY+TTjGNhQHbhOyS9Xdm+N/A9RxCSOWxjWeH8bpTKxNSGtFLZcCMocb6ykYWsz2vTd53TLuQKBgQDioOsjjtROonqYPKnhmEgOLY8VgwFH4xmzAjFuq/6yX6CdPBf6s575TV5kew9+UbnQQ3AXH1lX4yuw5nds/swi1gya+IC3RWEdBJD6YhyeRJQRWJh8q0fNBX7SEfXUtcAx/vjerC0552nTKOpOd7Ry/f6P26Tfcu5+mhB85gf3FwKBgQCWmsvF+Qz4MO9Wuc0jfC5Snpdx5jGqY0Iik6TJXVjE6h6JvO6X4RUAAZASNftlQLY080ny8iqh/RGg1W1ym8tstvi3thZ0b9BPH2DpB+xAh8E/dChSNrRiJr6SiNFMTsOGXtoVXZgE2JjSRAqlQaiB2WZq7f3X8/Szf8MOn6bM9QJ/MnWh5Ujn/JowsbTQHmrJoF6EfUWuA1ONZU4Xs4yYKR8ho+C9dhSIUPnpCnZb/MQ1myloy70vJ2JtV/X4oUwaJ6eBJwAtqKDJ/qwFm7o8pQCf9zzCtv9r/To8Aon9Ml9Fa9xZjTrI1xuvdFSn1tDQXMow49cD3ry4XXfwM98D5wKBgD22ir/CET12l+ya0GO1FCpI0Fgc8scWS1ht1b2p4aE3KnJYmBBmbDuHaGj989kGzmMeOnQyJaQhVmLociPfkVkoFPz6wXLPCrYRbp2u4HGE73w39fnSbtI1fCwBono5YEekgIr2wj9iHiUzOoWDRTCITD6O7VDbp68SMHTCmRAtAoGBAN71/mXkmubvG5hjd74SSa3n0tzFJvWwCq0X8lkLnDqL+c5BW87q2dCJcXuSk5OJwTOE6n0KILbq/vHtaKfkV4QBdOzS8AQCDIY26zxauR4+fAhtMeBXjc4bjoHv6/6WRuCUZysBxYbOe7LEkEr1jmsN6SrYAGBRZlyPcAd31ccf";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showShort("充值成功");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                UserMsg userMsg = new UserMsg();
                                userMsg.setId(user.getId());
                                userMsg.setUsername(user.getUsername());
                                userMsg.setPassword(user.getPassword());
                                userMsg.setPrice(user.getPrice() + price);
                                UserMsgUtils.getInstance().getDaoSession().update(userMsg);
                            }
                        }).start();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort("支付失败!请稍后再试");
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                UserMsg userMsg = new UserMsg();
//                                userMsg.setId(user.getId());
//                                userMsg.setUsername(user.getUsername());
//                                userMsg.setPassword(user.getPassword());
//                                userMsg.setPrice(user.getPrice() + price);
//                                UserMsgUtils.getInstance().getDaoSession().update(userMsg);
//                            }
//                        }).start();
//                        UserMsg userMsg = new UserMsg();
//                        userMsg.setPrice(200);
//                        UserMsgUtils.getInstance().getDaoSession().queryBuilder().where(UserMsgDao.Properties.Id.eq(3)).unique().setPrice(100);
                    }
                    break;
                }
            }
            /**
             * 支付宝支付业务示例
             */

        }
    };

    public void payV2(int price) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {

            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, price, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}

